package com.example.mvc.context;

import com.example.common.utils.Statistics;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class MyHandlerInterceptor implements HandlerInterceptor {

    private static volatile MyHandlerInterceptor instance;

    private MyHandlerInterceptor(){
        Statistics.logInfo(log);
    }

    public static MyHandlerInterceptor getInstance(){
        if (instance == null) {
            synchronized (MyHandlerInterceptor.class){
                if (instance == null){
                    instance = new MyHandlerInterceptor();
                }
            }
        }
        return instance;
    }

    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                             @NonNull Object handler) throws Exception {
        Statistics.logInfo(log, "preHandle", request);
        return true;
    }

    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                           @NonNull Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        Statistics.logInfo(log, "postHandle", response);
    }

    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                                @NonNull Object handler, @Nullable Exception ex) throws Exception {
        Statistics.logInfo(log, "afterCompletion", response);
    }
}
